package com.example.dell.ssm.view;

import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.dell.ssm.R;
import com.jaydenxiao.common.commonutils.LogUtils;


/**
 * Created by dell on 2017/6/9.
 */

public class RefreshLayout extends LinearLayout implements View.OnTouchListener, RefreshLayoutLister {

    /**
     * 下拉状态
     */
    public static final int STATUS_PULL_TO_REFRESH = 0;

    /**
     * 下拉释放状态
     */
    public static final int STATUS_RELEASE_TO_REFRESH = 1;

    /**
     * 正在刷新
     */
    public static final int STATUS_REFRESHING = 2;

    /**
     * 正常没有刷新
     */
    public static final int STATUS_NORMAL = 3;

    /**
     * 头部参数
     */
    private MarginLayoutParams headLayoutParams;

    /**
     * 头高度
     */
    private float headerHeight;

    /**
     * 当前状态
     */
    private int currentStatus = STATUS_NORMAL;

    /**
     * 上次状态
     */
    private int lastStatus = currentStatus;


    /**
     * 首次按下y坐标
     */
    private float downY;

    /**
     * y轴移动距离
     */
    private float moveY;


    /**
     * 是否加载过onlayout(制允许加载一次)
     */
    private boolean loadOnce;

    /**
     * 是否可以刷新
     */
    private boolean canRefresh;

    /**
     * 子布局类型
     */
    private int childType;

    /**
     * 下拉头部回滚的速度
     */
    public static final int SCROLL_SPEED = -20;

    private boolean isCanRefresh;

    private PullToRefreshLister lister;

    private View headView;
    private ProgressBar headPb;
    private TextView headTv;
    private ListView listView;
    private RecyclerView recyclerView;
    private int status;
    private View firstView;
    private int firstVisiblePosition;
    private LinearLayout linearLayout;
    private RelativeLayout relativeLayout;
    private ScrollView scrollView;


    public RefreshLayout(Context context) {
        this(context, null);
    }

    public RefreshLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RefreshLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        headView = LayoutInflater.from(context).inflate(R.layout.header_layout, null);
        headPb = (ProgressBar) headView.findViewById(R.id.head_pb);
        headTv = (TextView) headView.findViewById(R.id.head_tv);
        setOrientation(VERTICAL);
        addView(headView, 0);
    }

    public RefreshLayout setLister(PullToRefreshLister lister) {
        this.lister = lister;
        return this;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        super.onLayout(changed, l, t, r, b);
        if (changed && !loadOnce) {
            headerHeight = -headView.getHeight();
            LogUtils.loge(headerHeight + "  headerheight");
            headLayoutParams = (MarginLayoutParams) headView.getLayoutParams();
            headLayoutParams.topMargin = (int) headerHeight;
            headView.setLayoutParams(headLayoutParams);
            status = initView();
            if (status == 1) {
                listView.setOnTouchListener(this);
            } else if (status == 2) {
                recyclerView.setOnTouchListener(this);
            }
            loadOnce = true;
        }

    }


    @Override
    public boolean isRefreshing() {
        if (currentStatus == STATUS_REFRESHING) {
            return true;
        }
        return false;
    }

    @Override
    public void startRefresh() {
        new RefreshingTask(0).execute();
    }

    @Override
    public void stopRefresh() {
        new HideHeaderTast().execute();
    }

    @Override
    public void setCanRefresh(boolean canRefresh) {
        this.isCanRefresh = canRefresh;
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        setCanRefresh(event);
        if (canRefresh) {
            float distance = 0;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    moveY = event.getRawY();
                    distance = moveY - downY;
                    //如果手指上滑,头部隐藏的话就屏蔽下拉监听
                    if (distance <= 0 && headLayoutParams.topMargin <= headerHeight) {
                        return false;
                    }
                    if (currentStatus != STATUS_REFRESHING) {
                        if (headLayoutParams.topMargin > 0) {
                            currentStatus = STATUS_RELEASE_TO_REFRESH;
                        } else {
                            currentStatus = STATUS_PULL_TO_REFRESH;
                        }
                        headLayoutParams.topMargin = (int) ((distance / 2) + headerHeight);
                        headView.setLayoutParams(headLayoutParams);
                    }
                    LogUtils.loge(distance / 2 + "move  移动距离");
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    LogUtils.loge(distance / 2 + "upupup  移动距离");
                default: {
                    distance = moveY - downY;
                    LogUtils.loge(distance / 2 + "up   移动距离");
                    if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
                        // 松手时如果是释放立即刷新状态，就去调用正在刷新的任务
                        new RefreshingTask((int) (distance / 2)).execute();
                    } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
                        // 松手时如果是下拉状态，就去调用隐藏下拉头的任务
                        new RefreshingTask((int) (distance / 2)).execute();
                    }
                }
            }
        }
        return false;
    }

    private int initView() {
//        try {
//            listView = (ListView) getChildAt(1);
//            return 1;
//        } catch (Exception e) {
//            e.printStackTrace();
//            try {
//                recyclerView = (RecyclerView) getChildAt(1);
//                LogUtils.loge("2222");
//            } catch (Exception e1) {
//                e1.printStackTrace();
//                System.out.println("不是列表类型的view");
//            }
//            return 2;
//        }
        String simpleName = getChildAt(1).getClass().getSimpleName();
        switch (simpleName) {
            case "ListView":
                listView = (ListView) getChildAt(1);
                return childType = 1;
            case "RecyclerView":
                recyclerView = (RecyclerView) getChildAt(1);
                return childType = 2;
            case "LinearLayout":
                linearLayout = (LinearLayout) getChildAt(1);
                return childType = 3;
            case "RelativeLayout":
                relativeLayout = (RelativeLayout) getChildAt(1);
                return childType = 4;
            case "ScrollView":
                scrollView = (ScrollView) getChildAt(1);
                return childType = 5;
        }
        return childType;
    }

    /**
     * 根据当前ListView的滚动状态来设定 {@link #canRefresh}
     * 的值，每次都需要在onTouch中第一个执行，这样可以判断出当前应该是滚动ListView，还是应该进行下拉。
     *
     * @param event
     */
    private void setCanRefresh(MotionEvent event) {
        if (isCanRefresh) {

            switch (childType) {
                case 1:
                    firstView = listView.getChildAt(0);
                    firstVisiblePosition = listView.getFirstVisiblePosition();
                    if (firstView != null) {

                        //listview是否到顶部
                        if (firstVisiblePosition == 0 && firstView.getTop() == 0) {
                            if (!canRefresh) {
                                downY = event.getRawY();
                            }
                            canRefresh = true;
                        } else {
                            if (headLayoutParams.topMargin != headerHeight) {
                                headLayoutParams.topMargin = (int) headerHeight;
                                headView.setLayoutParams(headLayoutParams);//将headview至于可见布局之上
                            }
                            canRefresh = false;
                        }
                    } else {
                        canRefresh = true;
                    }
                    break;
                case 2:
                    firstView = recyclerView.getChildAt(0);
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    firstVisiblePosition = linearLayoutManager.findFirstVisibleItemPosition();
                    if (firstView != null) {

                        //listview是否到顶部
                        if (firstVisiblePosition == 0 && firstView.getTop() == 0) {
                            if (!canRefresh) {
                                downY = event.getRawY();
                            }
                            canRefresh = true;
                        } else {
                            if (headLayoutParams.topMargin != headerHeight) {
                                headLayoutParams.topMargin = (int) headerHeight;
                                headView.setLayoutParams(headLayoutParams);//将headview至于可见布局之上
                            }
                            canRefresh = false;
                        }
                    } else {
                        canRefresh = true;
                    }
                    break;
                case 4:
                case 3:
                    canRefresh = true;
                    break;
                case 5:
                    if (scrollView.getScaleY() == 0) {
                        canRefresh = true;
                    } else {
                        canRefresh = false;
                    }
                    break;
            }

        } else {
            canRefresh = false;
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class HideHeaderTast extends AsyncTask<Void, Integer, Integer> {
        @Override
        protected Integer doInBackground(Void... params) {
            int topMargin = headLayoutParams.topMargin;
            while (true) {
                topMargin += SCROLL_SPEED;
                if (topMargin <= headerHeight) {
                    topMargin = (int) headerHeight;
                    break;
                }
                publishProgress(topMargin);
                sleep(10);

            }
            return topMargin;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            headLayoutParams.topMargin = values[0];
            headView.setLayoutParams(headLayoutParams);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            headLayoutParams.topMargin = integer;
            headView.setLayoutParams(headLayoutParams);
            currentStatus = STATUS_NORMAL;
        }
    }

    /**
     * 正在刷新的任务，在此任务中会去回调注册进来的下拉刷新监听器。
     *
     * @author guolin
     */
    class RefreshingTask extends AsyncTask<Integer, Integer, Void> {
        private int distance;

        public RefreshingTask(int distance) {
            this.distance = distance;
        }

        @Override
        protected Void doInBackground(Integer... params) {
            int topMargin = (int) headerHeight + distance;
            LogUtils.loge((distance > -headerHeight) + "   hfurhufhr");
            if (distance > (-headerHeight)) {
                while (true) {
                    topMargin = topMargin + SCROLL_SPEED;
                    LogUtils.loge(topMargin + "-=-=-=-=-=-=-");
                    if (topMargin <= 0) {
                        topMargin = 0;
                        publishProgress(0);
                        break;
                    }
                    publishProgress(topMargin);
                    sleep(10);
                }
            } else {
                while (true) {
                    topMargin = topMargin - SCROLL_SPEED;
                    if (topMargin >= 0) {
                        topMargin = 0;
                        publishProgress(topMargin);
                        break;
                    }
                    publishProgress(topMargin);
                    sleep(10);
                }
            }
            currentStatus = STATUS_REFRESHING;
            publishProgress(0);
            if (lister != null) {
                lister.onRefresh();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... topMargin) {
            headLayoutParams.topMargin = topMargin[0];
            headView.setLayoutParams(headLayoutParams);
        }

    }

    public interface PullToRefreshLister {
        void onRefresh();
    }

}
